package com.shyroke.daydayzhuanweb.controller;

import com.shyroke.daydayzhuanapi.constant.ProjectConst;
import com.shyroke.daydayzhuanapi.dto.*;
import com.shyroke.daydayzhuanapi.entity.NewsEntity;
import com.shyroke.daydayzhuanapi.entity.SubmitArtEntity;
import com.shyroke.daydayzhuanapi.entity.UserEntity;
import com.shyroke.daydayzhuandao.respository.NewsRepository;
import com.shyroke.daydayzhuandao.respository.SubmitArtRepository;
import com.shyroke.daydayzhuandao.respository.UserRepository;
import com.shyroke.daydayzhuansvc.service.IOSSService;
import com.shyroke.daydayzhuansvc.service.MailService;
import com.shyroke.daydayzhuansvc.service.SubmitArtService;
import com.shyroke.daydayzhuansvc.service.impl.ProjectService;
import com.shyroke.daydayzhuansvc.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author youhj
 * @date 2019/10/25 0025 下午 1:20
 */
@Controller
@RequestMapping(value = "/admin/submitArtAdmin")
public class AdminSubmitArtController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IOSSService ossService;
//    @Autowired
//    private SubmitArtMapper submitArtMapper;
    @Autowired
    private SubmitArtRepository submitArtRepository;
    @Autowired
    private SubmitArtService submitArtService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private MailService mailService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private NewsRepository newsRepository;

    /**
     * 保存商务合作内容的图片
     * @param file
     * @return
     */
    @RequestMapping(value = "uploadImg")
    @ResponseBody
    public LayEditRespon uploadImg(MultipartFile file){
        LayEditRespon respon = new LayEditRespon();

        if(file.isEmpty()){
            respon.setCode(-1);
            respon.setMsg("图片为空");
            return respon;
        }

        String fileName = file.getOriginalFilename();

        //获取上传图片的后缀，比如.png,.jpg
        String img_suff = fileName.substring(fileName.lastIndexOf("."),fileName.length());

        //获取随机产生的图片名字
        String saveFileName = RandomUtil.getRandomFileName()+img_suff;

        String path = OSSClientConstants.SubmitAtr_PATH+CommonUtil.getDateByFormat(new Date(),"yyyy-MM-dd")+"/"+saveFileName;
        String url;
        try {
            ossService.uploadImg(file,path);
            url = ossService.getImgUrl(path);
            //加水印
            url = url + OSSClientConstants.WATER_MARK;
        }catch (Exception e){
            logger.info(ExceptionUtil.getMessage(e));
            respon.setCode(-1);
            respon.setMsg("图片上传失败");
            return respon;
        }

        Map<String,Object> data = new HashMap<String,Object>();

        data.put("src",url);

        respon.setCode(0);
        respon.setMsg("保存成功");
        respon.setData(data);

        return respon;
    }


    /**
     * 跳转到投稿管理的页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "list")
    public ModelAndView list(ModelAndView model) {
        model.setViewName("admin/submitArtAdmin/list");
        return model;
    }

    /**
     * 加载项目的数据
     *
     * @return
     */
    @RequestMapping(value = "getProjectList")
    @ResponseBody
    public TabelData<SubmitArtAdminDto> getProjectList(Page page, SubmitArt submitArt, String author) {
        if(!StringUtils.isEmpty(author)){
            UserEntity user = userRepository.findByName(author);
            submitArt.setUser(user);
        }
        return  submitArtService.getProjectListAdmin(page,submitArt);

    }

    @RequestMapping(value = "/{id}")
    public ModelAndView descAndEdit(@PathVariable("id")Integer id, ModelAndView model){
        SubmitArtEntity submitArt = null;
        Optional<SubmitArtEntity> optionalSubmitArtEntity = submitArtRepository.findById(id);
        if (optionalSubmitArtEntity.isPresent()) {
            submitArt = optionalSubmitArtEntity.get();
        }
        model.addObject("submitArt",submitArt);
        model.setViewName("admin/submitArt/artEdit");

        return model;

    }


    /**
     * 修改项目
     * @param art
     * @return
     */
    @PermissionAnnotation(permissionName = "submitArt:update")
    @RequestMapping(value = "update")
    @ResponseBody
    public R update(@RequestBody SubmitArt art){
        try {
            Optional<SubmitArtEntity> optionalSubmitArtEntity = submitArtRepository.findById(art.getId());
            if (optionalSubmitArtEntity.isPresent()) {
                SubmitArtEntity submitArtEntity = optionalSubmitArtEntity.get();
                submitArtEntity.setUpdateTime(new Date());
                submitArtEntity.setContent(art.getContent());
                submitArtEntity.setKeyword(art.getKeyword());
                submitArtEntity.setSummary(art.getSummary());
                submitArtEntity.setTitle(art.getTitle());
                submitArtEntity.setTypes(art.getTypes());
                submitArtRepository.save(submitArtEntity);
            }
        }catch (Exception e){
            logger.info(ExceptionUtil.getMessage(e));
            return R.error("修改失败，原因="+e.getMessage());
        }
        return R.ok("修改成功！");
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @PermissionAnnotation(permissionName = "submitArt:delete")
    @RequestMapping(value = "delete")
    @ResponseBody
    public R delete(Integer id,HttpSession session){
        UserMain user = (UserMain)session.getAttribute("user");
        Optional<SubmitArtEntity> optionalSubmitArtEntity = submitArtRepository.findById(id);
        if (optionalSubmitArtEntity.isPresent()) {
            SubmitArtEntity submitArtEntity = optionalSubmitArtEntity.get();
            if(!submitArtEntity.getCreateId().equals(user.getId())){
                return R.error("拥有者错误!");
            }
            submitArtRepository.deleteById(id);
        }
        return R.ok("删除成功！");
    }


    /**
     * 审核通过
     * @param id
     * @return
     */
    @PermissionAnnotation(permissionName = "submitArt:check")
    @RequestMapping(value = "pass")
    @ResponseBody
    @Transactional
    public R pass(Integer id){
        Optional<SubmitArtEntity> optionalSubmitArtEntity = submitArtRepository.findById(id);
        if(!optionalSubmitArtEntity.isPresent()){
            return R.error("id不存在实体");
        }
        SubmitArtEntity art = optionalSubmitArtEntity.get();
        art.setIsCheck(1);
        art.setMemo(null);

        try {
            ProjectDto project = new ProjectDto();
            BeanUtils.copyProperties(art,project);
            project.setId(null);
            project.setType(ProjectConst.NORMAL_PROJECT); //标志为普通项目
            project.setReadMount(0);//阅读数量
            project.setCommentMount(0);//评论数量
            project.setOffline(ProjectConst.UNOFFLINE); //默认未下架
            project.setTypes(art.getTypes().toString());
            project.setIsHomePage("1");
            project.setCreateTime(new Date());
            project.setIsNofollow(0);

            //上传到自己OSS
            ossService.handleImg(project,null);

            int projectId = projectService.save(project);
            art.setProjectId(projectId);
            submitArtRepository.save(art);

            NewsEntity news = CommonUtil.createNews("您的投稿已经审核通过，文章标题为："+project.getTitle(),project.getCreateId(),"4");
            newsRepository.save(news);

            //发送邮件
            Optional<UserEntity> optionalUserEntity = userRepository.findById(project.getCreateId());
            if(optionalUserEntity.isPresent()){
                UserEntity user = optionalUserEntity.get();
                mailService.sendNewProjectSuccess(user.getEmail(),project.getTitle());
            }
        }catch (Exception e){
            logger.info("审核失败，",e);
            return R.error("审核失败");
        }

        return R.ok("操作成功！");
    }


    /**
     * 审核失败
     * @param id
     * @return
     */
    @PermissionAnnotation(permissionName = "submitArt:check")
    @RequestMapping(value = "fail")
    @ResponseBody
    public R fail(Integer id,HttpSession session,String memo){
        Optional<SubmitArtEntity> optionalSubmitArtEntity = submitArtRepository.findById(id);
        if(!optionalSubmitArtEntity.isPresent()){
            return R.error("id不存在实体");
        }
        SubmitArtEntity art = optionalSubmitArtEntity.get();
        art.setIsCheck(2);
        art.setMemo(memo);
        try {
            submitArtRepository.save(art);
            NewsEntity news = CommonUtil.createNews("您的投稿审核失败，文章标题为："+art.getTitle()+",失败原因="+memo,art.getCreateId(),"4");
            newsRepository.save(news);
            //发送邮件
            Optional<UserEntity> optionalUserEntity = userRepository.findById(art.getCreateId());
            if(optionalUserEntity.isPresent()){
                UserEntity user = optionalUserEntity.get();
                mailService.sendNewProjectFail(user.getEmail(),art.getTitle(),memo);
            }

        }catch (Exception e){
            logger.info("审核失败，",e);
            return R.error("审核失败");
        }

        return R.ok("操作成功！");
    }

}
